﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using IPR_StudyMeetingMrgSys.ViewModel;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.BLL;
using IPR_StudyMeetingMrgSys.Model;
using Newtonsoft.Json;
using log4net;
using System.Reflection;
using System.Data;
using System.Web;
using System.IO;
using IPR_StudyMeetingMrgSys.Common;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    /// <summary>
    /// 资料试题控制器
    /// </summary>
    public class TrainQuestionController : ApiController
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        public string Get(int AutoID)
        {
            Model.TrainQuestion memp = new Model.TrainQuestion();
            memp = new BLL.TrainQuestion().GetModel(AutoID);
            return JsonConvert.SerializeObject(memp);
        }

        /// <summary>
        /// 文件试题明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainQuestion/GetTrainQuestionDetail")]
        public IHttpActionResult GetTrainQuestionDetail(long TFID)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                DataTable dt = new BLL.TrainQuestion().GetList(" IsUse=1 and TFID="+ TFID.ToString()).Tables[0];
                resultMsg.Info = dt.Rows.Count > 0 ? StatusCodeEnum.Success.GetEnumText() : "未获取到相应数据";
                resultMsg.Count = dt.Rows.Count;
                resultMsg.Data = dt;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }


        /// <summary>
        /// 文件试题明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainQuestion/GetSingleTrainQuestion")]
        public IHttpActionResult GetSingleTrainQuestion(long TQID)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                DataTable dt = new BLL.TrainQuestion().GetList(" IsUse=1 and TQID=" + TQID.ToString()).Tables[0];
                resultMsg.Info = dt.Rows.Count > 0 ? StatusCodeEnum.Success.GetEnumText() : "未获取到相应数据";
                resultMsg.Count = dt.Rows.Count;
                resultMsg.Data = dt;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 试题增加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainQuestion/Add")]
        public IHttpActionResult Add(Model.TrainQuestion model)
        {
            log.Info(JsonConvert.SerializeObject(model));
            
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                BLL.TrainQuestion bTpq = new BLL.TrainQuestion();
                if (!bTpq.Exists(model.Question))
                {
                    model.TQID = new BLL.SysManage().GetMaxId("TrainQuestion", "TQID");
                    model.IsUse = 1;
                    if (new IPR_StudyMeetingMrgSys.BLL.TrainQuestion().Add(model)>0)
                    {
                        resultMsg.Info = "增加成功";
                        resultMsg.Count = 1;
                    }
                    else
                    {
                        resultMsg.Info = "增加失败";
                    }
                }
                else
                {
                    resultMsg.Info = "试题信息已经存在，请不要重复增加";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        // POST: api/TrainQuestion
        /// <summary>
        /// 人员信息分页查找
        /// </summary>
        /// <param name="swhere">查询条件</param>
        /// <param name="page">页索引</param>
        /// <param name="limit">页大小</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainQuestion/Search")]
        public IHttpActionResult Search(string swhere, int page, int limit)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;
                if (!string.IsNullOrEmpty(swhere == null ? string.Empty : swhere.Trim()))
                {
                    Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                    swhere = string.Empty;
                    swhere = " IsUse=1 ";
                    foreach (var item in jsonObject)
                    {
                        if (item.Key == "FTID")
                        {
                            if (!string.IsNullOrEmpty( item.Value ))
                                swhere += $" and T.FTID = '{item.Value}'";
                        }
                        if (item.Key == "KKID")
                        {
                            if (!string.IsNullOrEmpty(item.Value))
                                swhere += $" and T.KKID = '{item.Value}'";
                        }
                        if (item.Key == "TQID")
                        {
                            if (!string.IsNullOrEmpty(item.Value))
                                swhere += $" and TQID = '{item.Value}'";
                        }
                        if (item.Key == "Question")
                        {
                            if (!string.IsNullOrEmpty(item.Value))
                                swhere += $" and Question LIKE '%'{item.Value}'%'";
                        }
                        if (item.Key == "QueType")
                        {
                            if (!string.IsNullOrEmpty(item.Value))
                                swhere += $" and QueType = '{item.Value}'";
                        }
                    }
                }
                int rowCount = 0;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainQuestion().GetListByPage(swhere, "AutoID", startindex, endindex, out rowCount);
                resultMsg.Info = rowCount > 0 ? StatusCodeEnum.Success.GetEnumText() : "未获取到相应数据";
                resultMsg.Count = rowCount;
                resultMsg.Data = dsSearch.Tables[0];
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
         
         
        [HttpGet]
        [Route("api/TrainQuestion/DelList")]
        public IHttpActionResult DelList(string delidlist)
        {
            log.Info(JsonConvert.SerializeObject(delidlist));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.TrainQuestion().DeleteList(delidlist))
                {
                    resultMsg.Info = "删除成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "删除失败";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }


        // PUT: api/T_TrainQuestion/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/T_TrainQuestion/5
        public void Delete(int id)
        {
        }
        #region 题目信息上传
        [HttpPost]
        [Route("api/TrainQuestion/Upload")]
        public IHttpActionResult FileUpload()
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {

                var FTID = HttpContext.Current.Request["FTID"].ToString();
                var KKID = HttpContext.Current.Request["KKID"].ToString();
                var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                if (file != null && file.ContentLength > 0)
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);
                    string path = HttpContext.Current.Server.MapPath("~/UploadTemp");
                    Directory.CreateDirectory(path);
                    file.SaveAs(Path.Combine(path, fileName));
                    ExcelHelper excelHelper = new ExcelHelper(Path.Combine(path, fileName));
                    DataTable dataTable = excelHelper.ExcelToDataTable(0, 1);
                    if (dataTable.Rows.Count == 0)
                    {
                        resultMsg.Info = "未获取到上传数据";
                        return Json(resultMsg);
                    }

                    foreach (DataRow dr in dataTable.Rows)
                    {
                        Model.TrainQuestion mTQ = new Model.TrainQuestion();

                        mTQ.TQID = new BLL.SysManage().GetMaxId("TrainQuestion", "TQID");
                        //string sFTName = dr[1].ToString(); 
                        //string sKKName = dr[2].ToString(); 
                        string sQueType = dr[1].ToString();
                        mTQ.QueType = GetUploadETID(sQueType);
                        mTQ.Question= dr[2].ToString();
                        mTQ.OptionA = dr[3].ToString();
                        mTQ.OptionB = dr[4].ToString();
                        mTQ.OptionC = dr[5].ToString();
                        mTQ.OptionD = dr[6].ToString();
                        mTQ.Answer = dr[7].ToString(); 
                        mTQ.QueValue = dr[8].ToString()==""?0:Convert.ToInt16(dr[8].ToString());
                        mTQ.IsUse = 1;
                        mTQ.KKID = Convert.ToInt16(KKID);
                        mTQ.FTID = Convert.ToInt16(FTID);
                        //Model.TrainFileType mTFY = new BLL.TrainFileType().GetModel(sFTName);
                        //if(mTFY==null)
                        //{
                        //    mTFY = new Model.TrainFileType();
                        //    mTFY.FTName = sFTName;
                        //    mTFY.FTDescribe = sFTName;
                        //    mTQ.FTID = new BLL.SysManage().GetMaxId("TrainFileType", "FTID");
                        //    new BLL.TrainFileType().Add(mTFY);
                        //}
                        //else
                        //{
                        //    mTQ.FTID = mTFY.FTID;
                        //}

                        //Model.TrainFileKnowledgeKey mTFKK = new BLL.TrainFileKnowledgeKey().GetModel(sKKName);
                        //if (mTFKK == null)
                        //{
                        //    mTFKK = new Model.TrainFileKnowledgeKey();
                        //    mTFKK.KKName = sKKName;
                        //    mTFKK.KKDescribe = sKKName;
                        //    mTQ.KKID = new BLL.SysManage().GetMaxId("TrainFileKnowledgeKey", "KKID");
                        //    new BLL.TrainFileKnowledgeKey().Add(mTFKK);
                        //}
                        //else
                        //{
                        //    mTQ.KKID = mTFKK.KKID;
                        //}

                        if (! new BLL.TrainQuestion().Exists(mTQ.Question))
                            new BLL.TrainQuestion().Add(mTQ);
                    }
                    resultMsg.Info = "上传成功";
                    resultMsg.Count = dataTable.Rows.Count;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "上传的文件为空";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 获取上传数据的试题类型
        /// </summary>
        /// <param name="ETName">试题类型名称</param>
        /// <returns></returns>
        private int GetUploadETID(string ETName)
        {
            switch (ETName)
            {
                case "选择题":
                    return 1;
                case "判断题":
                    return 2;
                case "填空题":
                    return 3;
                case "简答题":
                    return 4;
                case "综合题":
                    return 5;
                default:
                    return 0;
            }
        }
        #endregion
    }
}
